/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.disco.gco.view;

import com.jjsoft.disco.gco.mdl.Productobarra;
import com.jjsoft.disco.gco.ngc.ProductoBarraManager;
import com.jjsoft.disco.gco.ngc.ProductoManager;
import com.jjsoft.disco.gco.rep.CReportes;
import com.jjsoft.disco.gco.util.CNumeros;
import com.jjsoft.disco.gco.util.CSelecciones;
import com.jjsoft.disco.gco.util.MiModelo;
import com.jjsoft.disco.gco.util.configuraciones;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import net.sf.jasperreports.engine.JRException;

/**
 *
 * @author Johnny
 */
public class VAgregarProductoBarra extends javax.swing.JFrame {

    /**
     * Creates new form VAgregarProductoBarra
     */
    List<Productobarra> listaDetalle;
    MiModelo modelo = new MiModelo();
    HashMap<Integer, Double> cantidades;
    ProductoBarraManager pbm = new ProductoBarraManager();
    int barra;

    public VAgregarProductoBarra(int barra) {
        initComponents();
        cantidades = new HashMap<Integer, Double>();

        String[] identificadores = {"CANT", "DESCRIPCION", "P. UNIT"};
        this.barra = barra;
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgFactura.setModel(this.modelo);
        listaDetalle = pbm.cargarProductos(barra);
        if (listaDetalle == null) {
            listaDetalle = new ArrayList<Productobarra>();
        } else {
            for (int i = 0; i < listaDetalle.size(); i++) {
                cantidades.put(listaDetalle.get(i).getIdProducto().getIdProductos(), listaDetalle.get(i).getCantidad());
            }
            cargarDatos();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel9 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JSpinner();
        cmdAgregar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgFactura = new javax.swing.JTable();
        cmdGuardar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cmdDevolverBodega = new javax.swing.JButton();
        cmdDevolverTodoBodega = new javax.swing.JButton();
        cmdExportar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel9.setText("Codigo:");

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel10.setText("Cantidad:");

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        dtgFactura.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgFactura);

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 204));
        jLabel1.setText("Asignar Productos a las Barras");

        cmdDevolverBodega.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdDevolverBodega.setText("DEVOLVER A BODEGA");
        cmdDevolverBodega.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDevolverBodegaActionPerformed(evt);
            }
        });

        cmdDevolverTodoBodega.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdDevolverTodoBodega.setText("DEVOLVER TODO A BODEGA");
        cmdDevolverTodoBodega.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDevolverTodoBodegaActionPerformed(evt);
            }
        });

        cmdExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/pdf.png"))); // NOI18N
        cmdExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmdGuardar)
                        .addGap(2, 2, 2)
                        .addComponent(cmdDevolverBodega, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdDevolverTodoBodega)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdExportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 572, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(206, 206, 206)
                            .addComponent(jLabel10)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(139, 139, 139)
                            .addComponent(cmdAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jLabel9)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(140, 140, 140))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel9)
                        .addComponent(jLabel10)
                        .addComponent(cmdAgregar)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmdDevolverBodega, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdDevolverTodoBodega, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmdGuardar)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(cmdExportar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        setSize(new java.awt.Dimension(608, 389));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {
            CSelecciones.producto = new ProductoManager().buscarPorCodigo(txtCodigo.getText());
            if (CSelecciones.producto != null) {
//                txtPrecio.setText(CSelecciones.producto.getPrecioVenta().toString());
            } else {
                JOptionPane.showMessageDialog(rootPane, "No se ha encontrado un producto con ese codigo", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:

        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto2 = new JTextField();
        new VSeleccionArticulo(false).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.producto != null) {
            double precio = 0;
            int cantidad = Integer.parseInt(txtCantidad.getValue().toString());
            try {
                //precio = Double.parseDouble(txtPrecio.getText()) / (configuraciones.iva / 100D + 1);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Campo precio incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            boolean existe = false;
            for (int i = 0; i < listaDetalle.size(); i++) {
                if (listaDetalle.get(i).getIdProducto().equals(CSelecciones.producto)) {

                    existe = true;
                    double nuevaCantidad = 0;
                    nuevaCantidad = listaDetalle.get(i).getCantidad() + cantidad;
                    if (nuevaCantidad <= CSelecciones.producto.getStock()) {
                        listaDetalle.get(i).setCantidad(nuevaCantidad);
                        dtgFactura.setValueAt(String.valueOf(nuevaCantidad), i, 0);
//                        dtgFactura.setValueAt(String.valueOf(CNumeros.redondear((double)nuevaCantidad*precio)), i, 3);

                        CSelecciones.producto = null;
                        txtCantidad.setValue(1);
                        //txtPrecio.setText("");
                        txtCodigo.setText("");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "No existen suficientes productos en stock", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                }
            }
            if (!existe) {
                if (cantidad <= CSelecciones.producto.getStock()) {
                    agregarProducto(cantidad, CSelecciones.producto.getPrecioVenta());
                } else {
                    JOptionPane.showMessageDialog(rootPane, "No existen suficientes productos en stock", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha seleccionado un producto", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here:
        if (this.listaDetalle.size() > 0) {
            if (JOptionPane.showConfirmDialog(this.rootPane, "Está seguro de guardar los datos a las barras?", "Guardar Barras", 1) == 0) {

                pbm.guardarProductos(listaDetalle, cantidades);
                JOptionPane.showMessageDialog(rootPane, "Asignacion Guardada");
                VMantenimientoProductos.getInstance().actializaStocks();
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this.rootPane, "No se han agregado articulos a la factura", "Error", 0);
        }
    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void cmdDevolverBodegaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDevolverBodegaActionPerformed
        // TODO add your handling code here:
        if (dtgFactura.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro?", "Devolver a bodega", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                devolverProducto(dtgFactura.getSelectedRow());
                VMantenimientoProductos.getInstance().actializaStocks();
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero seleccione un producto");
        }
    }//GEN-LAST:event_cmdDevolverBodegaActionPerformed

    private void cmdDevolverTodoBodegaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDevolverTodoBodegaActionPerformed
        // TODO add your handling code here:
        if(listaDetalle!=null && !listaDetalle.isEmpty())
        {
            if(JOptionPane.showConfirmDialog(rootPane, "Esta seguro?","Devolver todo a bodega",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
            {
                while(!listaDetalle.isEmpty())
                {
                    devolverProducto(0);
                    VMantenimientoProductos.getInstance().actializaStocks();
                }
            }
        }
    }//GEN-LAST:event_cmdDevolverTodoBodegaActionPerformed

    private void cmdExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdExportarActionPerformed
        try {
            // TODO add your handling code here:
            new CReportes().reporteBarra(listaDetalle, barra);
        } catch (JRException ex) {
            Logger.getLogger(VAgregarProductoBarra.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_cmdExportarActionPerformed

    /**
     * @param args the command line arguments
     */
    public void agregarProducto(int cantidad, double precio) {
        Productobarra detalle = new Productobarra();
        detalle.setCantidad((double) cantidad);
        detalle.setIdProducto(CSelecciones.producto);
        detalle.setIdBarra(barra);
        listaDetalle.add(detalle);
        String[] Articulo = {String.valueOf(cantidad), CSelecciones.producto.getDescripcion(), CNumeros.redondear(precio) + ""};
        modelo.addRow(Articulo);
        CSelecciones.producto = null;
        txtCantidad.setValue(1);
//        txtPrecio.setText("");
        txtCodigo.setText("");

    }

    public void cargarDatos() {
        for (int i = 0; i < listaDetalle.size(); i++) {
            String[] Articulo = {CNumeros.Formato(listaDetalle.get(i).getCantidad()), listaDetalle.get(i).getIdProducto().getDescripcion(), CNumeros.Formato(listaDetalle.get(i).getIdProducto().getPrecioVenta())};
            modelo.addRow(Articulo);
        }
        CSelecciones.producto = null;

    }
    private void devolverProducto(int index)
    {
        if (listaDetalle.get(index).getIdproductoBarra() != null) {
                listaDetalle.get(index).setCantidad(cantidades.get(listaDetalle.get(index).getIdProducto().getIdProductos()));
                pbm.devolverProducto(listaDetalle.get(index));
                listaDetalle.remove(index);
                modelo.removeRow(index);
                } else {
                    listaDetalle.remove(index);
                    modelo.removeRow(index);
                }
    }
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VAgregarProductoBarra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VAgregarProductoBarra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VAgregarProductoBarra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VAgregarProductoBarra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VAgregarProductoBarra(2).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdDevolverBodega;
    private javax.swing.JButton cmdDevolverTodoBodega;
    private javax.swing.JButton cmdExportar;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JTable dtgFactura;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCodigo;
    // End of variables declaration//GEN-END:variables
}
